package com.stt.mapper;

import com.stt.entity.Course;
import com.stt.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface CourseMapper {

    @Select("SELECT * FROM courses WHERE id = #{id}")
    Course findById(Integer id);

    // 根据id查询课程及其教师信息
    @Select("SELECT c.*, u.username as instructor_name, u.email as instructor_email " +
            "FROM courses c " +
            "LEFT JOIN users u ON c.instructor_id = u.id " +
            "WHERE c.id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "description", column = "description"),
            @Result(property = "instructorId", column = "instructor_id"),
            @Result(property = "instructor", column = "instructor_id",
                    one = @One(select = "com.stt.mapper.UserMapper.findById"))
    })
    Course findByIdWithInstructor(Integer id);

    // 根据id查询课程及其选课学生
    @Select("SELECT c.* FROM courses c WHERE c.id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "description", column = "description"),
            @Result(property = "instructorId", column = "instructor_id"),
            @Result(property = "students", column = "id",
                    many = @Many(select = "com.stt.mapper.CourseMapper.findStudentsByCourseId"))
    })
    Course findByIdWithStudents(Integer id);

    @Select("SELECT u.* FROM users u " +
            "INNER JOIN enrollments e ON u.id = e.user_id " +
            "WHERE e.course_id = #{courseId}")
    List<User> findStudentsByCourseId(Integer courseId);
}
